package org.sixtynine.stock.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.sixtynine.stock.Constants;
import org.sixtynine.stock.cache.CompanyCache;
import org.sixtynine.stock.cache.SectorCache;
import org.sixtynine.stock.entity.User;
import org.sixtynine.stock.service.StockPersistentService;
import org.sixtynine.stock.service.content.DataManagerService;
import org.sixtynine.stock.util.SecurityUtil;
import org.sixtynine.stock.util.SessionBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Thilanka
 * 
 */
@Controller
public class LoginController extends AbstractFrontController {

	@Autowired
	private StockPersistentService stockPersistentService;

	@Autowired
	private CompanyCache companyCache;

	@Autowired
	private SectorCache sectorCache;

	@Autowired
	private DataManagerService dataManagerService;

	/** name of the admin user */
	private String adminUser;

	/*
	 * This method use to set user category adding view
	 */
	@RequestMapping(value = "/login/login")
	public ModelAndView addLoginPage(HttpServletRequest request) {
		// create user category adding view
		ModelAndView modelAndView = new ModelAndView("login/login");
		// assign user category object to view
		modelAndView.addObject("registedUser", new User());

		String message = request.getParameter("message");
		modelAndView.addObject("message", message);

		return modelAndView;
	}

	@RequestMapping(value = "/admin/admin_home")
	public ModelAndView showAdmin(HttpServletRequest request) {

		ModelAndView modelAndView = null;
		SessionBean sessionBean = SessionBean.getInstance(request);
		if (sessionBean.getUser() != null) {
			modelAndView = new ModelAndView("/admin/admin_home");
		} else {
			modelAndView = new ModelAndView("/login/login");
			modelAndView.addObject("registedUser", new User());
		}

		return modelAndView;
	}

	@RequestMapping(value = "/login/login/process", method = RequestMethod.POST)
	public ModelAndView loginSucsses(@ModelAttribute User registedUser,
			HttpServletRequest request) {

		User user = stockPersistentService.findUserByUserName(registedUser
				.getUserName());

		ModelAndView modelAndView = null;

		// user not created
		if (user == null) {
			modelAndView = new ModelAndView("login/login");
			modelAndView.addObject("registedUser", new User());
			modelAndView
					.addObject("message",
							"User not exist. If you are not registerd, please register first");
			return modelAndView;
		}

		if (SecurityUtil.checkPassword(registedUser.getPassword(),
				user.getPassword())) {
			// add to session
			SessionBean sessionBean = SessionBean.getInstance(request);
			sessionBean.setAttr(SessionBean.USER, user);

			if (user.getUserCategory().getName().equals(getAdminUser())) {
				modelAndView = new ModelAndView("/admin/admin_home");
			} else {
				// send to free user home page
				modelAndView = new ModelAndView("/home");
				showBannar(modelAndView);
			}

			modelAndView.addObject("userName", user.getUserName());
			modelAndView.addObject("userLogged", true);
			modelAndView.addObject(Constants.MESSAGE,
					"User successfully logged in.");

		} else {
			modelAndView = new ModelAndView("login/login");
			modelAndView.addObject("registedUser", new User());

			modelAndView
					.addObject(Constants.MESSAGE,
							"Login failed. Please enter correct user name and password.");

		}
		return modelAndView;

	}

	public String getAdminUser() {
		return adminUser;
	}

	public void setAdminUser(String adminUser) {
		this.adminUser = adminUser;
	}

	@RequestMapping(value = "logout")
	public ModelAndView logOut(HttpServletRequest request) {

		ModelAndView modelAndView = null;
		HttpSession session = request.getSession(false);
		if (session != null) {
			session.invalidate();
			modelAndView = new ModelAndView("login/login");

			// assign user category object to view
			modelAndView.addObject("registedUser", new User());
			modelAndView.addObject(Constants.MESSAGE, "Login.");
		}

		return modelAndView;
	}

	@RequestMapping(value = "/clear_cash")
	public ModelAndView clearCache(HttpServletRequest request) {
		ModelAndView modelAndView = null;
		SessionBean sessionBean = SessionBean.getInstance(request);
		if (sessionBean.getUser() != null) {
			modelAndView = new ModelAndView("/admin/admin_home");
			
			// clear the cache
			companyCache.refresh(Constants.COMPANY_CACHED_DATA);
			sectorCache.refresh(Constants.SECTOR_CACHED_DATA);

			dataManagerService.init();
			
			modelAndView.addObject(Constants.MESSAGE,
					"The caches refreshed successfully");
		} else {
			modelAndView = new ModelAndView("/login/login");
			modelAndView.addObject("registedUser", new User());
		}

		return modelAndView;
	}

}
